//
//  AppDelegate.m
//  xhnApp
//
//  Created by voc on 2016/10/18.
//  Copyright © 2016年 voc. All rights reserved.
//
////////
#import "AppDelegate.h"

#import <JPush/JPUSHService.h>
#import <WXCloudModuleBaseConfig/WXUserInfoManager.h>
#import <WXCloudModuleBaseConfig/WXCloudModuleNotificationKey.h>
#import <WXCloudModuleCustomView/MainTabViewController.h>
#import <WXCloudModuleCustomView/WXNewFeatureViewController.h>
#import <WXCloudModuleCustomView/WXPopViewTools.h>
#import <WXCloudModuleCustomView/WXLaunchADManager.h>
#import <WXCloudModuleCustomView/WXUpdateManager.h>
#import <WXCloudModuleBaseConfig/WXWaveRefreshManager.h>
#import <WXCloudModuleBaseConfig/WXCloudModuleUserDefaultsManager.h>
#import <WXCloudModuleMediator/WXMediator+WXMediatorModuleManager.h>
#import <WXCloudModuleMediator/WXMediator+WXMediatorModuleShareActions.h>
#import <WXCloudModuleMediator/WXMediator+WXMediatorModulePersonalActions.h>
#import <WXCloudModuleMediator/WXMediator+WXMediatorModuleNotificationActions.h>
#import <WXCloudModuleCustomFramework/IQKeyboardManager.h>
#import <WXCloudModuleNetworking/WXAppContext.h>

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#define SUPPORT_IOS8 0
#define JPushAppKey @"b64696b523991a34b9605ea5"

@interface AppDelegate () <JPUSHRegisterDelegate>

/// 通知监听对象
@property (nonatomic, strong) id observer;

@end

@implementation AppDelegate


+ (id)ShareDelegate
{
    return [UIApplication sharedApplication].delegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    UIViewController * rootController = [self defaultRootViewController];
    self.window.rootViewController = rootController;
    
    __weak typeof(self) weakSelf = self;
    self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:WXSwitchRootViewControllerNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        // 如果通知的 object 不为空，加载主界面
        if ([note.object isKindOfClass:[WXNewFeatureViewController class]]) {
            weakSelf.window.rootViewController = [self setupMainviewController];
            [[NSNotificationCenter defaultCenter] postNotificationName:kWXMainViewControllerDidAppearNotification object:nil];
        }
    }];
    
    [[WXMediator sharedInstance] moduleInit];
    
    [self JPushSdkInit:launchOptions];
    [self keyBoardManager];
    /*
     确保App启动的屏幕方向
     */
    //    [[UIApplication sharedApplication] setStatusBarOrientation:(UIInterfaceOrientationPortrait) animated:NO];
    
    //系统Badge
    UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    //由推送启动
    if (launchOptions!=nil) {
        NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        NSString *extras=[userInfo valueForKey:@"type"];
        if (extras!=nil) {
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
            }
            else{
                [[WXMediator sharedInstance]WXMediator_didReceiveRemoteNotificationAction:(UIApplication *)application userInfo:(NSDictionary *)userInfo];
            }
        }
    }
    else [[WXLaunchADManager sharedInstance] setupWXLaunchAd];
    
    [self.window makeKeyAndVisible];
    
    //注册响应后台控制
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
//    NSLog(@"UUID:%@",[WXAppContext sharedInstance].UDID);
//    NSLog(@"openUUID:%@",[WXUUID getUUID]);
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {

    [self.window endEditing:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[WXLaunchADManager sharedInstance] setupWXLaunchAd];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [[WXPopViewTools sharedInstance] showSpreadBoardTextView];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[WXAppContext sharedInstance] isCanPlayAudioAndVideo:NO];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    [[NSUserDefaults standardUserDefaults] setObject: deviceToken forKey:@"deviceToken"];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[WXMediator sharedInstance]WXMediator_didReceiveRemoteNotificationAction:(UIApplication *)application userInfo:(NSDictionary *)userInfo];
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[WXMediator sharedInstance]handleOpenURL:url];
    if (!result) {
        result = [[[WXMediator sharedInstance] performActionWithUrl:url completion:nil] boolValue];
    }
    
    return result;
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    BOOL result = [[WXMediator sharedInstance]handleOpenURL:url];
    if (!result) {
        result = [[[WXMediator sharedInstance] performActionWithUrl:url completion:nil] boolValue];
    }
    return result;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}


#pragma mark -默认根控制器
///
/// @return 系统启动的默认根控制器
- (UIViewController *)defaultRootViewController {
    return [self setupMainviewController];
    
    // 判断是否有新版本
//    if ([self isNewVersion]) {
//        return [WXNewFeatureViewController new];
//    } else {
//        return [self setupMainviewController];
//    }
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support//程序处于当前iOS10以上，前台得到的的通知对象
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
       [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 SupportiOS10及以上系统，后台得到的的通知对象(当用户点击通知栏的时候)
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [[WXMediator sharedInstance] WXMediator_didReceivePushToNewsDetailAction:(NSDictionary *)userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif

#pragma mark - private methods

/// 检查新版本
- (BOOL)isNewVersion {
    // 1. 取出当前版本
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    // 2. 取出沙盒版本
    NSString *sandboxVersionKey = @"WX_SandboxVersionKey";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *sandboxVersion = [defaults stringForKey:sandboxVersionKey];
    // 3. 将当前版本保存至用户偏好
    [defaults setObject:currentVersion forKey:sandboxVersionKey];
    return [currentVersion compare:sandboxVersion] == NSOrderedDescending;
}

-(UIViewController *)setupMainviewController
{
    //1、初始化控制器
    MainTabViewController *mainTab=[MainTabViewController sharedTabbar];
    _navController = [[UINavigationController alloc]initWithRootViewController:mainTab];
    [_navController setNavigationBarHidden: YES];
    //检查更新
//    [[WXUpdateManager sharedInstance] checkUpdate:^(NSDictionary *responseObject) {
//        //刷新字段数组
//        NSMutableArray *arr = [responseObject objectForKey:@"refresh_bg"];
//        [[WXWaveRefreshManager sharedInstance] reLoadDataSource:arr];
//        //刷新缓存
//        [[WXCloudModuleUserDefaultsManager sharedInstance] updateWithServerData:responseObject];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kWXRequestPartyCompleteNotification object:nil];
//        
//    } failure:^(NSString *errorMessage) {
//        
//    }];
    
//    [[WXMediator sharedInstance] WXMediator_updateSystemMessageState];
//    [[WXMediator sharedInstance] WXMediator_updateUserMessageState];
    
    return _navController;
}

//极光推送
-(void)JPushSdkInit:(NSDictionary *)launchOptions
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
    else{ //>= 8.0
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:@"appstore" apsForProduction:YES advertisingIdentifier:nil];
    [JPUSHService setDebugMode];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            if (registrationID!=nil) {
                [[NSUserDefaults standardUserDefaults] setObject: registrationID forKey:kWXUserInfoRegisterID];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}

- (void)keyBoardManager
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
}

@end
